package com.congee02.sw.var;

public class LongestOnes {

    public int longestOnes(int[] nums, int k) {

        int n = nums.length;

        // l = r = 0
        boolean f = nums[0] == 1;

        int zeros = f ? 0 : 1;

        if (n == 1) {
            return k >= zeros ? 1 : 0;
        }

        int ans = f ? 1 : 0;

        int l = 0;
        for (int r = 1 ; r < n ; r ++ ) {
            // 如果新加入的元素需要额外判断，那么先加入新元素
            if (nums[r] == 0) {
                zeros ++;
            }
            // 然后合法化窗口
            while (zeros > k) {
                if (nums[l ++] == 0) {
                    zeros --;
                }
            }
            ans = Math.max(ans, r - l + 1);
        }
        return ans;
    }

}
